package ru.ifmo.swing.genetics.automaton;

import org.uncommons.watchmaker.swing.EvolutionControl;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import ru.ifmo.automaton.Automaton;
import ru.ifmo.automaton.generators.custom.XmlAutomatonSourceExtractor;
import ru.ifmo.common.ObjectExtractor;
import ru.ifmo.common.Source;
import ru.ifmo.swing.EvolutionControlWithConfigProvider;
import ru.ifmo.swing.genetics.config.common.ChooserListener;
import ru.ifmo.swing.genetics.config.common.FileChooser;

import javax.swing.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author avhaliullin
 */
public class AutomatonFromFile implements Source<Automaton<Character, String>>, EvolutionControlWithConfigProvider {
    private final XmlAutomatonSourceExtractor<Character, String> automatonSourceExtractor = new XmlAutomatonSourceExtractor<Character, String>(
            new ObjectExtractor<Character, String>() {
                public Character extract(String source) {
                    return source.charAt(0);
                }
            },
            new ObjectExtractor<String, String>() {
                public String extract(String source) {
                    return source;
                }
            }
    );
    private FileChooser control;
    private Source<Automaton<Character, String>> source;

    {
        control = new FileChooser(new ChooserListener<File>() {
            public void chosen(File file) {
                try {
                    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
                    source = automatonSourceExtractor.extract(doc.getDocumentElement());
                } catch (SAXException e) {
                    //TODO: Oh no, handle that...
                } catch (IOException e) {
                    //TODO: Oh no, handle that...
                } catch (ParserConfigurationException e) {
                    //TODO: Oh no, handle that...
                }
            }
        });
    }

    public JComponent getControl() {
        return control;
    }

    public void reset() {
    }

    public void setDescription(String description) {
        control.setTitle(description);
    }

    public Automaton<Character, String> create() {
        return source.create();
    }

    public Map<String, Object> getParamValues() {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("File name", control.getFileName());
        return res;
    }
}
